package com.penghaisoft.microwms.base.web.auth.service.impl;

import com.penghaisoft.microwms.base.web.factory.dao.BaseFactoryGroupMapper;
import com.penghaisoft.microwms.base.web.factory.dao.BaseFactoryMapper;
import com.penghaisoft.microwms.base.web.factory.dao.BaseFactoryResourceMapper;
import com.penghaisoft.microwms.base.web.factory.dao.BaseFactoryUserMapper;
import com.penghaisoft.microwms.base.web.auth.service.IBaseFactoryService;
import com.penghaisoft.microwms.base.web.user.dao.BaseUserMapper;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.base.model.*;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.UserFactoryDto;
import com.penghaisoft.microwms.common.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 工厂服务
 * @author luoteng
 * @date 2017年5月24日 上午11:02:27
 * @version 1.0
 */
@Slf4j
@Service("baseFactoryService")
public class BaseFactoryServiceImpl extends BaseService implements
		IBaseFactoryService {
	@Resource
	private BaseFactoryMapper baseFactoryMapper;

	@Autowired
	private BaseFactoryUserMapper baseFactoryUserMapper;

	@Autowired
	private BaseFactoryResourceMapper factoryResourceMapper;

	@Autowired
	private BaseFactoryGroupMapper baseFactoryGroupMapper;
	
	@Autowired
	private BaseUserMapper baseUserMapper;
	
	/** 
	 * @Title create
	 * @Description 创建工厂
	 * @author luoteng
	 * @date 2017年5月24日 上午10:57:52
	 * @param baseFactory
	 * @return Resp
	 */
	@Transactional
	@Override
	public Resp create(BaseFactory baseFactory) {
		BaseFactory tmp = new BaseFactory();
		tmp.setFactoryCode(baseFactory.getFactoryCode());
		// 工厂编码 重复性校验
		int count = baseFactoryMapper.checkUnique(tmp);
		tmp = new BaseFactory();
		tmp.setFactoryName(baseFactory.getFactoryName());
		// 工厂名称重复性校验
		int countName = baseFactoryMapper.checkUnique(tmp);

		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		if (count != 0) {
			resp.setCode(Constant.FAIL);
			resp.setMsg("base.auth.factory.code.conflict");
			return resp;
		} else if (countName != 0) {
			resp.setCode(Constant.FAIL);
			resp.setMsg("base.auth.factory.name.conflict");
			return resp;
		} else {
			baseFactoryMapper.create(baseFactory);
			if (baseFactory.getGroupCode()!=null&&!"".equals(baseFactory.getGroupCode())) {
				assignGroupUserFactoryAdd(baseFactory);
			}
		}

		return resp;
	}
	
    /**
     * 新增工厂组工厂时，给新工厂分配用户
     * @param baseFactory
     */
    private void assignGroupUserFactoryAdd(BaseFactory baseFactory) {
//    	工厂组编码
		String factoryGroupCode = baseFactory.getGroupCode();
//		找到当前工厂组下的用户
		BaseUser cond = new BaseUser();
		cond.setFactoryGroupCode(factoryGroupCode);
		cond.setActiveFlag("1");
		List<BaseUser> users = baseUserMapper.queryUserUnderGroup(cond);
//		给新工厂插入工厂关联的用户
		List<BaseFactoryUserKey> factoryUserKeys = new ArrayList<BaseFactoryUserKey>();
		if (users!=null && users.size() > 0 ) {
//			构造插入对象
			for (BaseUser baseUser : users) {
				BaseFactoryUserKey baseFactoryUserKey = new BaseFactoryUserKey();
				baseFactoryUserKey.setFactoryId(baseFactory.getFactoryId());
				baseFactoryUserKey.setUserId(baseUser.getUserId());
				factoryUserKeys.add(baseFactoryUserKey);
			}
			baseFactoryUserMapper.insertFactoryUserBatch(factoryUserKeys);
		}
	}

	/** 
	 * @Title delete
	 * @Description 删除工厂
	 * @author luoteng
	 * @date 2017年5月24日 上午10:58:04
	 * @param baseFactory
	 * @return Resp
	 */
	@Override
	public Resp delete(BaseFactory baseFactory) {
		baseFactoryMapper.delete(baseFactory);
		return success();
	}

	/** 
	 * @Title findListByCondition
	 * @Description 获取工厂列表
	 * @author luoteng
	 * @date 2017年5月24日 上午10:58:16
	 * @param page
	 * @param rows
	 * @param condition
	 * @return Pager<BaseFactory>
	 */
	@Override
	public Pager<BaseFactory> findListByCondition(int page, int rows,
												  BaseFactory condition) {
		Pager<BaseFactory> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		List<BaseFactory> records = baseFactoryMapper.queryList(pager,
				condition);
		long size = baseFactoryMapper.queryCount(condition);
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/** 
	 * @Title findById
	 * @Description 根据工厂ID获取工厂信息
	 * @author luoteng
	 * @date 2017年5月24日 上午10:58:34
	 * @param id
	 * @return BaseFactory
	 */
	@Override
	public BaseFactory findById(String id) {
		return baseFactoryMapper.queryById(id);
	}

	/** 
	 * @Title update
	 * @Description 修改工厂信息
	 * @author luoteng
	 * @date 2017年5月24日 上午10:58:54
	 * @param baseFactory
	 * @return Resp
	 */
	@Transactional
	@Override
	public Resp update(BaseFactory baseFactory) {
		// 修改时 只校验 工厂名称 重复性校验
		int count = baseFactoryMapper.checkUpdUnique(baseFactory);
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		if (count != 0) {
			resp.setCode(Constant.FAIL);
			resp.setMsg("base.auth.factory.name.conflict");
		} else {
//			修改工厂时更新工厂组
			BaseFactory oldFactory = baseFactoryMapper.queryById(baseFactory.getFactoryId());
//	    	修改前工厂组编码
			String oldFactoryGroupCode = oldFactory.getGroupCode()==null?"":oldFactory.getGroupCode();
//	    	修改后工厂组编码
			String newFactoryGroupCode = baseFactory.getGroupCode()==null?"":baseFactory.getGroupCode();
			
			if (!oldFactoryGroupCode.equals(newFactoryGroupCode)) {
//				如果工厂组发生变化则更新工厂关联的用户
				assignGroupUserFactoryUpd(oldFactory, baseFactory);
			}
			baseFactoryMapper.updateBySelect(baseFactory);
			
		}

		return resp;
	}
	
	/**
	 * 更新工厂归属工厂组时，调整工厂用户关联关系
	 */
	private void assignGroupUserFactoryUpd(BaseFactory oldFactory,BaseFactory newFactory) {
//    	修改前工厂组编码
		String oldFactoryGroupCode = oldFactory.getGroupCode()==null?"":oldFactory.getGroupCode();
//    	修改后工厂组编码
		String newFactoryGroupCode = newFactory.getGroupCode()==null?"":newFactory.getGroupCode();
		if ("".equals(oldFactoryGroupCode)&&!"".equals(newFactoryGroupCode)) {
//			b1 如果从没有工厂组变为有工厂组--类似新增
//	    	工厂组编码
			String factoryGroupCode = newFactoryGroupCode;
//			找到当前工厂组下的用户
			BaseUser cond = new BaseUser();
			cond.setFactoryGroupCode(factoryGroupCode);
			cond.setActiveFlag("1");
			List<BaseUser> users = baseUserMapper.queryUserUnderGroup(cond);
			
			BaseFactory factoryCond = new BaseFactory();
			factoryCond.setActiveFlag("1");
			factoryCond.setGroupCode(factoryGroupCode);
			List<BaseFactory> groupFactories = baseFactoryMapper.queryByAny(factoryCond);
//			要加入的工厂
			groupFactories.add(newFactory);
			
			List<BaseFactoryUserKey> factoryUserKeys = new ArrayList<BaseFactoryUserKey>();
			if (users!=null && users.size() > 0 && groupFactories!=null && groupFactories.size()>0) {
//				构造插入对象
				for (BaseFactory baseFactory2 : groupFactories) {
					for (BaseUser baseUser : users) {
						BaseFactoryUserKey baseFactoryUserKey = new BaseFactoryUserKey();
						baseFactoryUserKey.setFactoryId(baseFactory2.getFactoryId());
						baseFactoryUserKey.setUserId(baseUser.getUserId());
						factoryUserKeys.add(baseFactoryUserKey);
					}
				}
				baseFactoryUserMapper.insertFactoryUserBatch(factoryUserKeys);
			}
			
		}else if (!"".equals(oldFactoryGroupCode)&&!"".equals(newFactoryGroupCode)) {
//			b2 如果从工厂组A变为有工厂组B
//			先删除A工厂组内的集团用户
			String factoryGroupCode = oldFactoryGroupCode;
//			找到工厂组下的用户
			BaseUser cond = new BaseUser();
			cond.setFactoryGroupCode(factoryGroupCode);
			cond.setActiveFlag("1");
			List<BaseUser> users = baseUserMapper.queryUserUnderGroup(cond);
			
			BaseFactory factoryCond = new BaseFactory();
			factoryCond.setActiveFlag("1");
			factoryCond.setGroupCode(factoryGroupCode);
			List<BaseFactory> groupFactories = baseFactoryMapper.queryByAny(factoryCond);
			
			List<BaseFactoryUserKey> factoryUserKeys = new ArrayList<BaseFactoryUserKey>();
			if (users!=null && users.size() > 0 && groupFactories!=null && groupFactories.size()>0) {
//				构造插入对象
				for (BaseFactory baseFactory2 : groupFactories) {
					for (BaseUser baseUser : users) {
						BaseFactoryUserKey baseFactoryUserKey = new BaseFactoryUserKey();
						baseFactoryUserKey.setFactoryId(baseFactory2.getFactoryId());
						baseFactoryUserKey.setUserId(baseUser.getUserId());
						factoryUserKeys.add(baseFactoryUserKey);
					}
				}
				for (BaseFactoryUserKey baseFactoryUserKey : factoryUserKeys) {
					
					baseFactoryUserMapper.deleteByPrimaryKey(baseFactoryUserKey);
				}
			}
			
//			再新增B的集团用户
			factoryGroupCode = newFactoryGroupCode;
//			找到当前工厂组下的用户
			cond = new BaseUser();
			cond.setFactoryGroupCode(factoryGroupCode);
			cond.setActiveFlag("1");
			users = baseUserMapper.queryUserUnderGroup(cond);
			
			factoryCond = new BaseFactory();
			factoryCond.setActiveFlag("1");
			factoryCond.setGroupCode(factoryGroupCode);
			groupFactories = baseFactoryMapper.queryByAny(factoryCond);
//			要加入的工厂
			groupFactories.add(newFactory);
			
			factoryUserKeys = new ArrayList<BaseFactoryUserKey>();
			if (users!=null && users.size() > 0 && groupFactories!=null && groupFactories.size()>0) {
//				构造插入对象
				for (BaseFactory baseFactory2 : groupFactories) {
					for (BaseUser baseUser : users) {
						BaseFactoryUserKey baseFactoryUserKey = new BaseFactoryUserKey();
						baseFactoryUserKey.setFactoryId(baseFactory2.getFactoryId());
						baseFactoryUserKey.setUserId(baseUser.getUserId());
						factoryUserKeys.add(baseFactoryUserKey);
					}
				}
				baseFactoryUserMapper.insertFactoryUserBatch(factoryUserKeys);
			}
		}else if (!"".equals(oldFactoryGroupCode)&&"".equals(newFactoryGroupCode)) {
//			b3 从工厂组A变为空
//			将A工厂组内的集团用户删除
//	    	工厂组编码
			String factoryGroupCode = oldFactoryGroupCode;
//			找到工厂组下的用户
			BaseUser cond = new BaseUser();
			cond.setFactoryGroupCode(factoryGroupCode);
			cond.setActiveFlag("1");
			List<BaseUser> users = baseUserMapper.queryUserUnderGroup(cond);
			
			BaseFactory factoryCond = new BaseFactory();
			factoryCond.setActiveFlag("1");
			factoryCond.setGroupCode(factoryGroupCode);
			List<BaseFactory> groupFactories = baseFactoryMapper.queryByAny(factoryCond);
			
			List<BaseFactoryUserKey> factoryUserKeys = new ArrayList<BaseFactoryUserKey>();
			if (users!=null && users.size() > 0 && groupFactories!=null && groupFactories.size()>0) {
//				构造插入对象
				for (BaseFactory baseFactory2 : groupFactories) {
					for (BaseUser baseUser : users) {
						BaseFactoryUserKey baseFactoryUserKey = new BaseFactoryUserKey();
						baseFactoryUserKey.setFactoryId(baseFactory2.getFactoryId());
						baseFactoryUserKey.setUserId(baseUser.getUserId());
						factoryUserKeys.add(baseFactoryUserKey);
					}
				}
				for (BaseFactoryUserKey baseFactoryUserKey : factoryUserKeys) {
					
					baseFactoryUserMapper.deleteByPrimaryKey(baseFactoryUserKey);
				}
			}
			
		}else {
//			不可能
			log.info("oldFactoryGroupCode:"+oldFactoryGroupCode+"   newFactoryGroupCode:"+newFactoryGroupCode);
		}
	}

	/** 
	 * @Title queryFactoryUserAll
	 * @Description 获取工厂下的人员，为空则取所有人
	 * @author zhangx
	 * @date 2017年5月24日 上午10:59:46
	 * @param condition
	 * @return List<BaseFactoryUser>
	 */
	@Override
	public List<BaseFactoryUser> queryFactoryUserAll(
			BaseFactoryUserKey condition) {
		return baseFactoryUserMapper.queryFactoryUser(condition);
	}

	/** 
	 * @Title updateFactoryUser
	 * @Description 更新工厂下的用户
	 * @author zhangx
	 * @date 2017年5月24日 上午11:00:22
	 * @param list
	 * @return Resp
	 */
	@Transactional
	@Override
	public Resp updateFactoryUser(List<BaseFactoryUserKey> list) {
		// 1.删除原来的工厂用户
		baseFactoryUserMapper.deleteByPrimaryKeyOne(list.get(0));
		if (!list.get(0).getUserId().equals("")) {
			// 2.新增新用户
			baseFactoryUserMapper.insertFactoryUserBatch(list);
		}
		return success();
	}

	/** 
	 * @Title queryByFactoryId
	 * @Description 根据工厂Id查询关联资源
	 * @author qh
	 * @date 2017年5月24日 上午11:01:11
	 * @param factoryId
	 * @return List<BaseFactoryResource>
	 */
	@Override
	public List<BaseFactoryResource> queryByFactoryId(String factoryId) {
		List<BaseFactoryResource> factoryResources = factoryResourceMapper
				.selectByFactoryId(factoryId);
		return factoryResources;
	}

	/** 
	 * @Title updateFacResRelation
	 * @Description 批量更新工厂资源关联信息
	 * @author qh
	 * @date 2017年5月24日 上午11:01:04
	 * @param factoryIds 工厂Id列表
	 * @param factoryResources 工厂资源关系列表
	 * @return Resp
	 */
	@Override
	@Transactional
	public Resp updateFacResRelation(List<String> factoryIds,
			List<BaseFactoryResource> factoryResources) {
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		factoryResourceMapper.deleteByFactoryIds(factoryIds);
		if (!factoryResources.isEmpty()) {
			factoryResourceMapper.insertBatch(factoryResources);
		}
		return resp;
	}

	/** 
	 * @Title queryFactoryTypeAll
	 * @Description 查询所有的工厂类型
	 * @author luoteng
	 * @date 2017年5月24日 上午11:01:40
	 * @return List<BaseFactory>
	 */
	@Override
	public List<BaseFactory> queryFactoryTypeAll() {
		return baseFactoryMapper.queryFactoryTypeAll();
	}

	/** 
	 * @Title queryFactoriesByType
	 * @Description 查询加工工厂
	 * @author pangxl
	 * @date 2017年11月9日 上午11:01:40
	 * @return List<BaseFactory>
	 */
	@Override
	public List<BaseFactory> queryFactoriesByType(String factoryType) {
		return baseFactoryMapper.queryFactoriesByType(factoryType);
	}
	
	/** 
	 * <p>Title: queryUserFactory</p> 
	 * <p>Description: 查询用户的工厂</p> 
	 * @Title: queryUserFactory 
	 * @Description: 查询用户的工厂
	 * @author zhangxu 
	 * @2017年6月6日:2017年6月6日:下午1:27:51
	 * @param @param userId
	 * @param @return       
	 * @throws 
	 * @version V0.1 
	 */
	@Override
	public List<BaseFactory> queryUserFactory(String userId) {
		List<BaseFactory> factories = baseFactoryMapper.queryUserFactoryByUserId(userId);
		return factories;
	}
	/** 
	 * @Title queryFactoryAll
	 * @Description 查询所有工厂
	 * @author jzh
	 * @return List<BaseFactory>
	 */

	@Override
	public List<BaseFactory> queryFactoryAll() {
		return baseFactoryMapper.queryFactoryAll();
		
	}
	



	/** 
	 * <p>Title: queryFactoryDtoByUser</p> 
	 * <p>Description: </p> 
	 * @Title: queryFactoryDtoByUser 
	 * @Description: 查询用户工厂信息
	 * @author zhangxu 
	 * @2017年6月30日:2017年6月30日:下午1:42:24
	 * @param @param userInfo
	 * @param @return       
	 * @throws 
	 * @version V0.1 
	 */
	@Override
	public List<UserFactoryDto> queryFactoryDtoByUser(BaseUser userInfo) {
		List<UserFactoryDto> userFactoryDtos = new ArrayList<>();
		List<BaseFactory> factories = baseFactoryMapper.queryUserFactoryByUserId(userInfo.getUserId());
		for (BaseFactory baseFactory : factories) {
			UserFactoryDto userFactoryDto = new UserFactoryDto();
			userFactoryDto.setFactoryId(baseFactory.getFactoryId());
			userFactoryDto.setFactoryCode(baseFactory.getFactoryCode());
			userFactoryDto.setFactoryName(baseFactory.getFactoryName());
			userFactoryDto.setFactoryType(baseFactory.getFactoryType());
			userFactoryDto.setDeptCode(baseFactory.getDeptCode());
			userFactoryDto.setDeliveryLoc(baseFactory.getUserDefined1());
			userFactoryDto.setGroupCode(baseFactory.getGroupCode());
			userFactoryDto.setIsOpenStorage(baseFactory.getIsOpenStorage());
			userFactoryDto.setDeliveryLocList(baseFactory.getUserDefined3());
//			List<BaseFactoryRsap> sapFactories = baseFactoryRsapMapper.queryByFactoryCode(baseFactory.getFactoryCode());
//			List<UserSapFactoryDto> sapDtos = new ArrayList<>();
//			for (BaseFactoryRsap baseFactoryRsap : sapFactories) {
//				UserSapFactoryDto userSapFactoryDto = new UserSapFactoryDto();
//				userSapFactoryDto.setSapFactoryCode(baseFactoryRsap.getSapFactoryCode());
//				userSapFactoryDto.setSapFactoryName(baseFactoryRsap.getSapFactoryName());
//				sapDtos.add(userSapFactoryDto);
//			}
//			userFactoryDto.setSapFactories(sapDtos);
			userFactoryDtos.add(userFactoryDto);
		}
		return userFactoryDtos;
	}


	@Override
	public List<BaseFactoryCodeInfo> queryCodeBySapFactoryCode(String sapFactoryCode) {
		return baseFactoryMapper.queryCodeBySapFactoryCode(sapFactoryCode);
	}
	
	/** 
	 * @Title queryFactoryType
	 * @Description 根据工厂号 查询 工厂类型
	 * @author luoteng
	 * @date 2017年11月9日:上午9:44:07
	 * @param factoryCode
	 * @return String
	 */
	public String queryFactoryType(String factoryCode){
		String factoryType = "";
		
		BaseFactory fac = new BaseFactory();
		fac.setFactoryCode(factoryCode);
		List<BaseFactory> list = baseFactoryMapper.queryByAny(fac);
		
		if(list != null && !list.isEmpty()){
			BaseFactory tmp = list.get(0);
			factoryType = tmp.getFactoryType();
		}
		return factoryType;
	}
	/**
	 * @Description: 查询工厂名称
	 * @param @param factoryCode
	 * @param @return   
	 * @author sun_yq
	 * @date 2017年11月16日 上午11:09:18
	 */
	@Override
	public List<BaseFactory> queryFactoryNameByFactoryCode(String factoryCode) {
		return baseFactoryMapper.queryFactoryNameByFactoryCode(factoryCode);
	}
	/**
	 * @Description: 查询工厂名称、仓库名称等信息
	 * @param @param factoryCode
	 * @param @return   
	 * @author sun_yq
	 * @date 2017年11月16日 上午11:09:37
	 */
	@Override
	public List<BaseFactoryNameInfo> queryNameByFactoryCode(String factoryCode) {
		return baseFactoryMapper.queryNameByFactoryCode(factoryCode);
	}
	
	/** 
	 * @Title isOpenStorage
	 * @Description 判断工厂是否开启库存
	 * @author luoteng
	 * @date 2017年11月24日:下午3:48:12
	 * @param factoryCode
	 * @return Boolean
	 */
	@Override
	public Boolean isOpenStorage(String factoryCode){
		Boolean flag = false;
		List<BaseFactory> facList = baseFactoryMapper.queryFactoryNameByFactoryCode(factoryCode);
		
		if(facList != null && !facList.isEmpty()){
			BaseFactory baseFac = facList.get(0);
//			开启库存 1是 0否
			if("1".equals(baseFac.getIsOpenStorage())){
				flag = true;
			}
		}
		return flag;
	}
	/**
	 * baseFactoryGroup  新增
	 */
	@Override
	public Resp createBaseFactoryGroup(BaseFactoryGroup baseFactoryGroup) {
		baseFactoryGroup.preQuery();
		baseFactoryGroupMapper.create(baseFactoryGroup);
		return success();
		
	}

	/**
	 * baseFactoryGroup 删除
	 */
	@Override
	public Resp deleBaseFactoryGroup(BaseFactoryGroup baseFactoryGroup) {
		baseFactoryGroupMapper.delete(baseFactoryGroup);
		return success();
	}

	/**
	 * baseFactoryGroup 查询列表
	 */
	@Override
	public Pager<BaseFactoryGroup> findListByGroupCondition(int page, int rows, BaseFactoryGroup condition) {
		Pager<BaseFactoryGroup> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		long size = baseFactoryGroupMapper.queryCount(condition);
		List<BaseFactoryGroup> group = new ArrayList<BaseFactoryGroup>();
		if(size>0){
			group= baseFactoryGroupMapper.queryList(pager, condition);
		}
		pager.setRecords(group);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * baseFactoryGroup 查询单条
	 */
	@Override
	public BaseFactoryGroup findBaseFactoryGroupById(String id) {
		return baseFactoryGroupMapper.queryById(id);
	}

	/**
	 * baseFactoryGroup 修改更新
	 */
	@Override
	public Resp updateBaseFactoryGroup(BaseFactoryGroup baseFactoryGroup) {
		baseFactoryGroupMapper.updateBySelect(baseFactoryGroup);
		return success();
	}

	/**
	 * 根据工厂组编码 查询 唯一
	 * groupCode
	 */
	@Override
	public BaseFactoryGroup findByGroupCode(String groupCode) {
		return baseFactoryGroupMapper.queryByGroupCode(groupCode);
	}

	/*
	 * 查询所有工厂组
	 * */
	@Override
	public List<BaseFactoryGroup> getGroups() {
		return 	baseFactoryGroupMapper.getGroups();
	}


}
